package com.nowcoder.community.controller.advice;

import com.nowcoder.community.util.CommunityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author 花木凋零成兰
 * @date 2024/3/16 17:52
 */
@ControllerAdvice(annotations = Controller.class)
@Slf4j(topic = "ExceptionAdvice.class")
public class ExceptionAdvice {

    @ExceptionHandler({Exception.class})
    public void handleException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        log.error("服务器发生异常：" + e.getMessage());
        for (StackTraceElement element : e.getStackTrace()) {   // 输出日志 异常详细信息
            log.error(element.toString());
        }

        String xRequestedWith = request.getHeader("x-requested-with");  // 希望返回的类型
        if ("XMLHttpRequest".equals(xRequestedWith)) { // 说明是异步请求
            response.setContentType("application/plain;charset=utf-8");   // 返回普通字符串 格式确认为JSON
            PrintWriter writer = response.getWriter();
            writer.write(CommunityUtil.getJSONString(1, "服务器异常!"));
        } else {
            response.sendRedirect(request.getContextPath() + "/error");     // 重定向
        }

    }

}
